package linkedlist.MyLinkedList;

class Node {
    public String value;

    public Node next;

    public Node(String value) {
        this.value = value;
        this.next = null;
    }
}

public class MyLinkedList {

    //头结点
    private Node head = null;

    //头插法
    public void addFirst(String data){
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }

    //尾插法
    public void addLast(String data){
        if (head == null) {
            Node newNode = new Node(data);
            head = newNode;
            return;
        }
        Node newNode = new Node(data);
        Node prev = head;
        for (;prev != null;prev = prev.next) {
            if (prev.next == null) {
                break;
            }
        }
        prev.next = newNode;
    }

    //任意位置插⼊,第⼀个数据节点为0号下标
    public void addIndex(int index,String data){
        if (index < 0 || index > size()){
            throw new IndexOutOfBoundsException("Index = " + index + ",size = " + size());
        }
        Node newNode = new Node(data);
        if (index == 0) {
            newNode.next = head;
            head = newNode;
            return;
        }
        Node prev = head;
        for (int i = 0;i < index - 1;i++) {
            prev = prev.next;
        }
        newNode.next = prev.next;
        prev.next = newNode;
    }

    public int size() {
        Node num;
        int size = 0;
        num = head;
        for (;num != null;num = num.next) {
            size++;
        }
        return size;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        Node prev = head;
        for (;prev != null;prev = prev.next) {
            stringBuilder.append(prev.value);
            if (prev.next != null) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }

    public static void Test1() {
        MyLinkedList list = new MyLinkedList();
        list.addFirst("a");
        list.addFirst("b");
        list.addFirst("c");
        list.addFirst("d");
        System.out.println(list);
    }

    public static void Test2() {
        MyLinkedList list = new MyLinkedList();
        list.addLast("a");
        list.addLast("b");
        list.addLast("c");
        list.addLast("d");
        System.out.println(list);
        System.out.println(list.size());
    }

    public static void Test3() {
        MyLinkedList list = new MyLinkedList();
        list.addLast("a");
        list.addLast("b");
        list.addLast("c");
        list.addLast("d");
        list.addIndex(3,"m");
        System.out.println(list);
    }

    public static void main(String[] args) {
        Test3();
    }
}
